﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DataLayer;
using C1.Win.C1FlexGrid;
using System.IO;
using System.Diagnostics;

namespace OrderDocument
{
    public partial class frmOrder : XtraForm
    {
        public frmOrder()
        {
            InitializeComponent();
        }
        public bool EskiEvrak { get; set; }
        bool kaydedildi = false;

        //private void CiroBilgisi()
        //{
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append("SELECT     isnull(CAST(SUM(ORDER_DETAILS.total) AS decimal(16, 2)),0) AS Tutar ");
        //    sb.Append(" FROM         ORDER_DETAILS ");
        //    sb.Append(" WHERE     (ORDER_DETAILS.customer_code = '{0}') ");
        //    decimal ciro = Convert.ToDecimal(Factory.GetFactory.ExecuteScaler(string.Format(sb.ToString(), System.Configuration.ConfigurationSettings.AppSettings["CariKodu"])));
        //    lblCiro2.Text = string.Format("{0} TL", ciro.ToString("#,##0.00"));
        //}


        private void frmOrder_Load(object sender, EventArgs e)
        {
            frmPassword pwd = new frmPassword();
            if (pwd.ShowDialog() != DialogResult.OK)
                Application.Exit();

            txtCariKod.Focus();
            c1FlexGrid1.Cols[3].AllowEditing = false;
            c1FlexGrid1.Cols[4].AllowEditing = false;
            c1FlexGrid1.Cols[8].AllowEditing = false;
            c1FlexGrid1.Cols[9].AllowEditing = false;
            c1FlexGrid1.Cols[10].Visible = false;
            c1FlexGrid1.Cols[11].Visible = false;
            c1FlexGrid1.Cols[12].Visible = false;

            labelControl14.Text = "Tedarikçi =  " + Factory.GetFactory.ExecuteScaler(string.Format("exec sp_executesql N'select name from CUSTOMERS where code=''{0}'''", System.Configuration.ConfigurationSettings.AppSettings["CariKodu"]));

            timer1.Enabled = false;
            timer1.Start();
        }

        private void txtCariKod_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                CariBul();
            }
            //else if (e.KeyCode == Keys.F10)
            //{
            //    frmListe liste = new frmListe();
            //    liste.ListeTipi = frmListe.ListeTipleri.CariKodu;
            //    liste.Filtre = txtCariKod.Text;
            //    if (liste.ShowDialog(this) == DialogResult.OK && liste.Value.Length > 0)
            //    {
            //        txtCariKod.Text = liste.Value[0];
            //        txtCariAd.Text = liste.Value[1];
            //        txtSeri.Text = liste.Value[2];
            //        c1FlexGrid1.Select(1, 0);
            //        c1FlexGrid1.Focus();
            //    }
            //}
        }

        private void CariBul()
        {
            dbListe liste = new dbListe();
            string[] bilgi = liste.CariUnvani(txtCariKod.Text).Split(';');
            if (bilgi != null)
            {
                if (bilgi.Length == 6)
                {
                    if (bilgi[2] == "yok")
                    {
                        MessageBox.Show("Cari Giriş’i Yapılmamış,Lutfen Kayıt bankosundan Giriş Yaptırınız.");
                    }
                    else
                    {
                        txtCariAd.Text = bilgi[0];
                        txtSeri.Text = bilgi[1];
                        if (!string.IsNullOrEmpty(txtSeri.Text))
                            initSeri();

                        txtAdres.Text = bilgi[3];
                        txtBolge.Text = bilgi[4];
                        txtTemsilci.Text = bilgi[5];
                        c1FlexGrid1.Focus();
                    }
                }
                else
                {
                    txtCariKod.Text = "";
                    txtCariAd.Text = "";
                    txtCariKod.Focus();
                    MessageBox.Show("Kayıt Bulunamadı !");
                }
            }
        }

        private void txtCariAd_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                c1FlexGrid1.Focus();
            }
            else if (e.KeyCode == Keys.F10)
            {
                if (txtCariAd.Text.Length > 2)
                {
                    frmListe liste = new frmListe();
                    liste.ListeTipi = frmListe.ListeTipleri.CariAdi;
                    liste.Filtre = txtCariAd.Text;
                    if (liste.ShowDialog(this) == DialogResult.OK && liste.Values.Count > 0)
                    {
                        txtCariKod.Text = liste.Values[0][0];
                        txtCariAd.Text = liste.Values[0][1];
                        txtSeri.Text = liste.Values[0][2];
                        CariBul();
                        c1FlexGrid1.Select(1, 0);
                        c1FlexGrid1.Focus();
                    }
                }
                else
                {
                    MessageBox.Show("Lütfen Ünvanın bir kısmını yazıp arama yapın !");
                }
            }
        }

        private void txtCariKod_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmListe liste = new frmListe();
            liste.ListeTipi = frmListe.ListeTipleri.CariKodu;
            liste.Filtre = txtCariKod.Text;
            if (liste.ShowDialog(this) == DialogResult.OK && liste.Values.Count > 0)
            {
                txtCariKod.Text = liste.Values[0][0];
                txtCariAd.Text = liste.Values[0][1];
                txtSeri.Text = liste.Values[0][2];
                if (!string.IsNullOrEmpty(txtSeri.Text))
                    initSeri();
                c1FlexGrid1.Select(1, 0);
                c1FlexGrid1.Focus();
            }
        }

        private void txtCariAd_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmListe liste = new frmListe();
            liste.ListeTipi = frmListe.ListeTipleri.CariAdi;
            liste.Filtre = txtCariAd.Text;
            if (liste.ShowDialog(this) == DialogResult.OK && liste.Values.Count > 0)
            {
                txtCariKod.Text = liste.Values[0][0];
                txtCariAd.Text = liste.Values[0][1];
                txtSeri.Text = liste.Values[0][2];
                if (!string.IsNullOrEmpty(txtSeri.Text))
                    initSeri();
                c1FlexGrid1.Select(1, 0);
                c1FlexGrid1.Focus();
            }
        }

        bool f10basildi = false;

        private void c1FlexGrid1_KeyDownEdit(object sender, C1.Win.C1FlexGrid.KeyEditEventArgs e)
        {
            if (e.KeyCode == Keys.F10 && c1FlexGrid1.Col < 2)
            {
                f10basildi = true;
                c1FlexGrid1.FinishEditing();
                f10basildi = false;
                frmListe liste = new frmListe();

                if (c1FlexGrid1.Col == 0)
                {
                    liste.ListeTipi = frmListe.ListeTipleri.StokKodu;
                    if (c1FlexGrid1[c1FlexGrid1.Row, 0] != null) liste.Filtre = c1FlexGrid1[c1FlexGrid1.Row, 0].ToString(); else liste.Filtre = "";
                }
                else
                {
                    liste.ListeTipi = frmListe.ListeTipleri.StokAdi;
                    if (c1FlexGrid1[c1FlexGrid1.Row, 1] != null) liste.Filtre = c1FlexGrid1[c1FlexGrid1.Row, 1].ToString(); else liste.Filtre = "";
                }
                if (liste.ShowDialog(this) == DialogResult.OK && liste.Values.Count > 0)
                {
                    int row = c1FlexGrid1.Row;
                    foreach (string[] item in liste.Values)
                    {
                        c1FlexGrid1[row, 9] = item[0];
                        c1FlexGrid1[row, 0] = item[1];
                        c1FlexGrid1[row, 1] = item[2];
                        if (c1FlexGrid1[row, 2] == null || Convert.ToDecimal(c1FlexGrid1[row, 2]) <= 0)
                        {
                            c1FlexGrid1[row, 2] = item[10];
                        }
                        c1FlexGrid1[row, 3] = item[9];
                        c1FlexGrid1[row, 4] = DovizKur(item[5]) * decimal.Parse(item[3]);
                        c1FlexGrid1[row, 10] = item[4];
                        c1FlexGrid1[row, 12] = item[5];
                        c1FlexGrid1[row, 5] = item[6];
                        c1FlexGrid1[row, 6] = item[7];
                        c1FlexGrid1[row, 7] = item[8];
                        c1FlexGrid1.Focus();
                        c1FlexGrid1.Select(row, 2);
                        row++;
                    }
                    SubTotal();
                }
            }
            else if (e.KeyCode == Keys.Enter && c1FlexGrid1.Col == 2)
                if (c1FlexGrid1.Row + 1 < c1FlexGrid1.Rows.Count)
                    c1FlexGrid1.Select(c1FlexGrid1.Row + 1, 0);

        }

        private void c1FlexGrid1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.F10 && c1FlexGrid1.Col < 2)
            {
                f10basildi = true;
                c1FlexGrid1.FinishEditing();
                f10basildi = false;
                frmListe liste = new frmListe();

                if (c1FlexGrid1.Col == 0)
                {
                    liste.ListeTipi = frmListe.ListeTipleri.StokKodu;
                    if (c1FlexGrid1[c1FlexGrid1.Row, 0] != null) liste.Filtre = c1FlexGrid1[c1FlexGrid1.Row, 0].ToString(); else liste.Filtre = "";
                }
                else
                {
                    liste.ListeTipi = frmListe.ListeTipleri.StokAdi;
                    if (c1FlexGrid1[c1FlexGrid1.Row, 1] != null) liste.Filtre = c1FlexGrid1[c1FlexGrid1.Row, 1].ToString(); else liste.Filtre = "";
                }
                if (liste.ShowDialog(this) == DialogResult.OK && liste.Values.Count > 0)
                {
                    int row = c1FlexGrid1.Row;
                    foreach (string[] item in liste.Values)
                    {
                        c1FlexGrid1[row, 9] = item[0];
                        c1FlexGrid1[row, 0] = item[1];
                        c1FlexGrid1[row, 1] = item[2];
                        if (c1FlexGrid1[row, 2] == null || Convert.ToDecimal(c1FlexGrid1[row, 2]) <= 0)
                        {
                            c1FlexGrid1[row, 2] = item[10];
                        }
                        c1FlexGrid1[row, 3] = item[9];
                        c1FlexGrid1[row, 4] = DovizKur(item[5]) * decimal.Parse(item[3]);
                        c1FlexGrid1[row, 10] = item[4];
                        c1FlexGrid1[row, 12] = item[5];
                        c1FlexGrid1[row, 5] = item[6];
                        c1FlexGrid1[row, 6] = item[7];
                        c1FlexGrid1[row, 7] = item[8];
                        c1FlexGrid1.Focus();
                        c1FlexGrid1.Select(row, 2);
                        row++;
                    }
                    SubTotal();
                }
            }
            else if (e.KeyCode == Keys.Delete)
            {
                c1FlexGrid1.Rows[c1FlexGrid1.Row].Clear(C1.Win.C1FlexGrid.ClearFlags.All);
                SubTotal();
            }
            else if (e.KeyCode == Keys.K && e.Alt == true)
            {
                frmYeniGiris yeni = new frmYeniGiris();
                yeni.EskiKayit = true;
                yeni.txtBarkod.Text = c1FlexGrid1[c1FlexGrid1.Row, 0].ToString();
                yeni.txtBarkod.Properties.ReadOnly = true;
                yeni.txtKodu.Properties.ReadOnly = true;
                yeni.barkodBul(c1FlexGrid1[c1FlexGrid1.Row, 9].ToString());
                yeni.txtBarkod.Focus();
                if (yeni.ShowDialog() == DialogResult.OK)
                    c1FlexGrid1[c1FlexGrid1.Row, 2] = yeni.Miktar;
            }
            else if (e.KeyCode == Keys.Enter && c1FlexGrid1.Col == 2)
                if (c1FlexGrid1.Row + 1 < c1FlexGrid1.Rows.Count)
                    c1FlexGrid1.Select(c1FlexGrid1.Row + 1, 0);


            if (e.Control == true && e.KeyCode == Keys.N)
                icerial();

        }

        void icerial()
        {
            MessageBox.Show("Dosya yapısı= barkod;miktar;fiyat şeklinde olmalıdır");

            OpenFileDialog dlg = new OpenFileDialog();
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                StreamReader sr = new StreamReader(dlg.FileName);
                string barkod = string.Empty;
                decimal fiyat = 0;
                decimal miktar = 0;
                string[] line;
                int index = 1;
                while (sr.Peek() > -1)
                {
                    line = sr.ReadLine().Split(';');
                    if (line.Length > 0)
                    {
                        barkod = line[0];
                        miktar = decimal.Parse(line[1]);
                        fiyat = decimal.Parse(line[2]);

                        string[] alanlar = null;
                        alanlar = dbListe.UrunBul(barkod);
                        if (alanlar != null)
                        {
                            if (alanlar.Length > 1)
                            {
                                c1FlexGrid1[index, 9] = alanlar[0];
                                c1FlexGrid1[index, 0] = alanlar[1];
                                c1FlexGrid1[index, 1] = alanlar[2];
                                c1FlexGrid1[index, 2] = miktar;
                                c1FlexGrid1[index, 3] = alanlar[9];
                                c1FlexGrid1[index, 4] = DovizKur(alanlar[5]) * fiyat;
                                c1FlexGrid1[index, 10] = alanlar[4];
                                c1FlexGrid1[index, 12] = alanlar[5];
                                c1FlexGrid1[index, 5] = alanlar[6];
                                c1FlexGrid1[index, 6] = alanlar[7];
                                c1FlexGrid1[index, 7] = alanlar[8];

                                index++;
                            }
                        }
                    }
                }
                sr.Close();
                SubTotal();
            }
        }



        private void SubTotal()
        {
            decimal fiyat = 0;
            decimal miktar = 0;
            decimal tutar = 0;
            decimal kdv_orani = 0;
            decimal kdv_tutar = 0;
            decimal geneltoplam = 0;
            decimal kdv_toplam = 0;
            decimal isk1oran;
            decimal isk2oran;
            decimal isk3oran;
            decimal isk1tutar;
            decimal isk2tutar;
            decimal isk3tutar;
            decimal genelisk1tutar = 0;
            decimal genelisk2tutar = 0;
            decimal genelisk3tutar = 0;


            for (int i = 1; i < c1FlexGrid1.Rows.Count; i++)
            {
                if (c1FlexGrid1[i, 0] != null)
                {
                    if (c1FlexGrid1[i, 2] != null) miktar = Convert.ToDecimal(c1FlexGrid1[i, 2]); else miktar = 0;
                    if (c1FlexGrid1[i, 4] != null) fiyat = Convert.ToDecimal(c1FlexGrid1[i, 4]); else fiyat = 0;
                    tutar = miktar * fiyat;
                    isk1oran = Convert.ToDecimal(c1FlexGrid1[i, 5]);
                    isk2oran = Convert.ToDecimal(c1FlexGrid1[i, 6]);
                    isk3oran = Convert.ToDecimal(c1FlexGrid1[i, 7]);
                    isk1tutar = tutar * isk1oran / 100;
                    isk2tutar = (tutar - isk1tutar) * isk2oran / 100;
                    isk3tutar = (tutar - isk1tutar - isk2tutar) * isk3oran / 100;
                    genelisk1tutar += isk1tutar;
                    genelisk2tutar += isk2tutar;
                    genelisk3tutar += isk3tutar;

                    tutar = tutar - isk1tutar - isk2tutar - isk3tutar;
                    c1FlexGrid1[i, 8] = tutar.ToString("#,###.00");

                    if (c1FlexGrid1[i, 10] != null) kdv_orani = Convert.ToDecimal(c1FlexGrid1[i, 10]); else kdv_orani = 0;
                    //kdv_orani = 0;
                    kdv_tutar = tutar * kdv_orani / 100;
                    c1FlexGrid1[i, 11] = kdv_tutar;

                    kdv_toplam += kdv_tutar;
                    geneltoplam += tutar;
                }
            }

            txtAraToplam.Text = (geneltoplam + genelisk1tutar + genelisk2tutar + genelisk3tutar).ToString("###,##0.00"); ;
            txtisk1.Text = genelisk1tutar.ToString("###,##0.00");
            txtisk2.Text = genelisk2tutar.ToString("###,##0.00");
            txtisk3.Text = genelisk3tutar.ToString("###,##0.00");
            txtNetToplam.Text = geneltoplam.ToString("###,##0.00");
            txtKdvToplam.Text = kdv_toplam.ToString("###,##0.00");
            txtGenelToplam.Text = (geneltoplam + kdv_toplam).ToString("###,##0.00");
        }


        private void c1FlexGrid1_AfterEdit(object sender, C1.Win.C1FlexGrid.RowColEventArgs e)
        {
            if (e.Col == 0 && string.IsNullOrEmpty(c1FlexGrid1[e.Row, e.Col].ToString()) == false && f10basildi == false)
            {
                string[] alanlar = null;
                if (c1FlexGrid1[e.Row, 0] != null) alanlar = dbListe.UrunBul(c1FlexGrid1[e.Row, 0].ToString());
                if (alanlar != null)
                {
                    if (alanlar.Length > 1)
                    {
                        c1FlexGrid1[c1FlexGrid1.Row, 9] = alanlar[0];
                        c1FlexGrid1[c1FlexGrid1.Row, 0] = alanlar[1];
                        c1FlexGrid1[c1FlexGrid1.Row, 1] = alanlar[2];
                        if (c1FlexGrid1[c1FlexGrid1.Row, 2] == null || Convert.ToDecimal(c1FlexGrid1[c1FlexGrid1.Row, 2]) <= 0)
                        {
                            c1FlexGrid1[c1FlexGrid1.Row, 2] = 1;
                        }
                        c1FlexGrid1[c1FlexGrid1.Row, 3] = alanlar[9];
                        c1FlexGrid1[c1FlexGrid1.Row, 4] = DovizKur(alanlar[5]) * decimal.Parse(alanlar[3]);
                        c1FlexGrid1[c1FlexGrid1.Row, 10] = alanlar[4];
                        c1FlexGrid1[c1FlexGrid1.Row, 12] = alanlar[5];
                        c1FlexGrid1[c1FlexGrid1.Row, 5] = alanlar[6].Replace('.', ',');
                        c1FlexGrid1[c1FlexGrid1.Row, 6] = alanlar[7].Replace('.', ',');
                        c1FlexGrid1[c1FlexGrid1.Row, 7] = alanlar[8].Replace('.', ',');
                    }
                    else
                    {
                        MessageBox.Show("Kaydetmek için yeni ürün butonuna tıklayınız !");
                    }
                }
                else
                {
                    MessageBox.Show("Kaydetmek için yeni ürün butonuna tıklayınız !");
                }
            }
            SubTotal();
        }

        private void YeniUrun()
        {
            string[] alanlar;
            frmYeniGiris yeni = new frmYeniGiris();
            if (c1FlexGrid1[c1FlexGrid1.Row, 0] != null && !string.IsNullOrEmpty(c1FlexGrid1[c1FlexGrid1.Row, 0].ToString()))
            {
                yeni.txtBarkod.Text = c1FlexGrid1[c1FlexGrid1.Row, 0].ToString();
            }
            yeni.txtBarkod.Focus();
            if (yeni.ShowDialog(this) == DialogResult.OK)
            {
                alanlar = dbListe.UrunBul(yeni.txtBarkod.Text);
                if (alanlar.Length > 1)
                {
                    c1FlexGrid1[c1FlexGrid1.Row, 9] = alanlar[0];
                    c1FlexGrid1[c1FlexGrid1.Row, 0] = alanlar[1];
                    c1FlexGrid1[c1FlexGrid1.Row, 1] = alanlar[2];
                    if (c1FlexGrid1[c1FlexGrid1.Row, 2] == null || Convert.ToDecimal(c1FlexGrid1[c1FlexGrid1.Row, 2]) <= 0)
                    {
                        c1FlexGrid1[c1FlexGrid1.Row, 2] = yeni.Miktar;
                    }
                    c1FlexGrid1[c1FlexGrid1.Row, 3] = alanlar[9];
                    c1FlexGrid1[c1FlexGrid1.Row, 4] = DovizKur(alanlar[5]) * decimal.Parse(alanlar[3]);
                    c1FlexGrid1[c1FlexGrid1.Row, 10] = alanlar[4];
                    c1FlexGrid1[c1FlexGrid1.Row, 12] = alanlar[5];
                    c1FlexGrid1[c1FlexGrid1.Row, 5] = alanlar[6].Replace('.', ',');
                    c1FlexGrid1[c1FlexGrid1.Row, 6] = alanlar[7].Replace('.', ',');
                    c1FlexGrid1[c1FlexGrid1.Row, 7] = alanlar[8].Replace('.', ',');
                }
            }
        }

        private void initSeri()
        {
            if (this.EskiEvrak == false)
            {
                string[] bilgi = dbListe.CariSeri(System.Configuration.ConfigurationSettings.AppSettings["CariKodu"]);
                if (!string.IsNullOrEmpty(bilgi[0]))
                {
                    txtSeri.Text = bilgi[0];
                    txtSira.Text = bilgi[2];
                }
            }
        }
        private string getVal(int row, int col)
        {
            string sonuc = string.Empty;
            if (c1FlexGrid1[row, col] != null)
                if (string.IsNullOrEmpty(c1FlexGrid1[row, col].ToString()) == false)
                    sonuc = c1FlexGrid1[row, col].ToString();
            return sonuc;
        }

        private int ConvertDoviz(string doviz)
        {
            switch (doviz)
            {
                case "TL":
                    return 0;
                case "USD":
                    return 1;
                case "EURO":
                    return 2;
                default:
                    return 0;
            }
        }

        private decimal DovizKur(string parabirimi)
        {
            object obj = Factory.GetFactory.ExecuteScaler("SELECT     rate  FROM         CURRENCY  WHERE     (name = '" + parabirimi + "')");
            decimal kur = 1;
            if (obj != null)
                kur = Convert.ToDecimal(obj);
            else
                kur = 1;
            return kur;
        }

        private bool columnCheck(int row, params int[] cols)
        {
            bool sonuc = true;
            foreach (int col in cols)
            {
                if (c1FlexGrid1[row, col] == null)
                {
                    sonuc = false;
                    break;
                }
                else
                {
                    if (string.IsNullOrEmpty(c1FlexGrid1[row, col].ToString()))
                        sonuc = false;
                }
            }
            return sonuc;
        }

        private void Kaydet()
        {
            if (!string.IsNullOrEmpty(txtCariKod.Text) && !string.IsNullOrEmpty(txtCariAd.Text))
            {
                EvrakKayit();

                DialogResult dlg = MessageBox.Show("Yazdırmak İstermisiniz ?", "", MessageBoxButtons.YesNo);
                if (dlg == DialogResult.Yes)
                {
                    Yazdir();
                }
                YeniEvrak();
            }
            else
                MessageBox.Show("Lütfen Cari Bilgilerini Girin !");
        }

        private void CekilisOlustur(string seri, int sira, string saglayici, string cari, string cekilisno, decimal tutar, IDbTransaction trn)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("if exists(select rec_id from CEKILIS_HAREKET where siparis_seri=@siparis_seri and siparis_no=@siparis_no )");
            sb.Append("update CEKILIS_HAREKET set saglayici=@saglayici,cari=@cari,siparis_tutari=@siparis_tutari,cekilis_no=@cekilis_no where siparis_seri=@siparis_seri and siparis_no=@siparis_no  else ");
            sb.Append("insert into CEKILIS_HAREKET (cari,saglayici,siparis_tutari,siparis_seri,siparis_no,cekilis_no) values (@cari,@saglayici,@siparis_tutari,@siparis_seri,@siparis_no,@cekilis_no) ");

            IDbDataParameter prm1 = Factory.GetFactory.GetParameter("@siparis_tutari", DbType.Decimal);
            IDbDataParameter prm2 = Factory.GetFactory.GetParameter("@cekilis_no", 25, DbType.String);
            IDbDataParameter prm3 = Factory.GetFactory.GetParameter("@siparis_seri", 5, DbType.String);
            IDbDataParameter prm4 = Factory.GetFactory.GetParameter("@siparis_no", DbType.Int32);
            IDbDataParameter prm5 = Factory.GetFactory.GetParameter("@cari", 25, DbType.String);
            IDbDataParameter prm6 = Factory.GetFactory.GetParameter("@saglayici", 25, DbType.String);

            prm1.Value = tutar;
            prm2.Value = cekilisno;
            prm3.Value = seri;
            prm4.Value = sira;
            prm5.Value = cari;
            prm6.Value = saglayici;

            Factory.GetFactory.ExecuteNonQuery(CommandType.Text, sb.ToString(), trn, prm1, prm2, prm3, prm4, prm5, prm6);
        }

        private void CekilisKontrol(decimal siparisTutari, string seri, int sira, string cari, IDbTransaction trn)
        {
            string cekilisNo = "";
            string supplier = System.Configuration.ConfigurationSettings.AppSettings["CariKodu"];
            IDbDataParameter prm1 = Factory.GetFactory.GetParameter("@tutar", DbType.Decimal);
            prm1.Value = siparisTutari;

            object sonuc = Factory.GetFactory.ExecuteScaler(CommandType.Text, string.Format("SELECT     cekilis_no  FROM         CEKILISLER WITH (NOLOCK)  WHERE     (tedarikci_kodu = '{0}') AND (cekilis_limit <= @tutar)", supplier), prm1);
            if (sonuc != null)
            {
                cekilisNo = sonuc.ToString();
                CekilisOlustur(seri, sira, supplier, cari, cekilisNo, siparisTutari, trn);
            }
        }


        private void EvrakKayit()
        {
            string order_series = txtSeri.Text;
            int order_no = int.Parse(txtSira.Text);
            DateTime order_date = DateTime.Now;
            string customer_code = txtCariKod.Text;

            string product_code = string.Empty;
            string barcode = string.Empty;
            decimal amount = decimal.MinValue;
            decimal price = decimal.MinValue;
            decimal total = decimal.MinValue;
            int vat = int.MinValue;
            decimal vatsum = decimal.MinValue;
            int currency = int.MinValue;
            decimal isk1;
            decimal isk2;
            decimal isk3;


            IDbTransaction trn = Factory.GetFactory.OpenSession();
            string insertSql = "insert into ORDER_DETAILS (order_series, order_no, order_date, customer_code, product_code, barcode, amount, price, total, vat, vatsum, currency,supplier,printed,discount1,discount2,discount3,comment) values (@order_series, @order_no, @order_date, @customer_code, @product_code, @barcode, @amount, @price, @total, @vat, @vatsum, @currency,@supplier,0,@isk1,@isk2,@isk3,@comment)";
            string deleteSql = " delete from ORDER_DETAILS where order_series=@order_series and order_no=@order_no";

            IDbDataParameter prm1 = Factory.GetFactory.GetParameter("@order_series", DbType.String);
            prm1.Value = order_series;
            IDbDataParameter prm2 = Factory.GetFactory.GetParameter("@order_no", DbType.Int32);
            prm2.Value = order_no;
            IDbDataParameter prm3 = Factory.GetFactory.GetParameter("@order_date", DbType.DateTime);
            prm3.Value = order_date;
            IDbDataParameter prm4 = Factory.GetFactory.GetParameter("@customer_code", DbType.String);
            prm4.Value = customer_code;
            IDbDataParameter prm5 = Factory.GetFactory.GetParameter("@product_code", DbType.String);
            IDbDataParameter prm6 = Factory.GetFactory.GetParameter("@barcode", DbType.String);
            IDbDataParameter prm7 = Factory.GetFactory.GetParameter("@amount", DbType.Decimal);
            IDbDataParameter prm8 = Factory.GetFactory.GetParameter("@price", DbType.Decimal);
            IDbDataParameter prm9 = Factory.GetFactory.GetParameter("@total", DbType.Decimal);
            IDbDataParameter prm10 = Factory.GetFactory.GetParameter("@vat", DbType.Int32);
            IDbDataParameter prm11 = Factory.GetFactory.GetParameter("@vatsum", DbType.Decimal);
            IDbDataParameter prm12 = Factory.GetFactory.GetParameter("@currency", DbType.Int32);
            IDbDataParameter prm13 = Factory.GetFactory.GetParameter("@supplier", DbType.String);
            IDbDataParameter prm14 = Factory.GetFactory.GetParameter("@isk1", DbType.Decimal);
            IDbDataParameter prm15 = Factory.GetFactory.GetParameter("@isk2", DbType.Decimal);
            IDbDataParameter prm16 = Factory.GetFactory.GetParameter("@isk3", DbType.Decimal);
            IDbDataParameter prm17 = Factory.GetFactory.GetParameter("@comment", 500, DbType.String);
            prm17.Value = txtAciklama.Text;


            prm13.Value = System.Configuration.ConfigurationSettings.AppSettings["CariKodu"];

            Factory.GetFactory.ExecuteNonQuery(CommandType.Text, deleteSql, trn, prm1, prm2); //kayıt vt silinir.


            for (int i = 1; i < c1FlexGrid1.Rows.Count; i++)
            {
                if (c1FlexGrid1[i, 0] != null)
                {
                    if (columnCheck(i, 0, 1, 2, 4, 5, 6) == true)
                    {
                        product_code = getVal(i, 0);
                        amount = decimal.Parse(getVal(i, 2));
                        price = decimal.Parse(getVal(i, 4));
                        isk1 = decimal.Parse(getVal(i, 5));
                        isk2 = decimal.Parse(getVal(i, 6));
                        isk3 = decimal.Parse(getVal(i, 7));
                        total = decimal.Parse(getVal(i, 8));
                        barcode = getVal(i, 9);
                        vat = int.Parse(getVal(i, 10));
                        vatsum = decimal.Parse(getVal(i, 11));
                        currency = ConvertDoviz(getVal(i, 12));

                        prm5.Value = product_code;
                        prm6.Value = barcode;
                        prm7.Value = amount;
                        prm8.Value = price;
                        prm9.Value = total;
                        prm10.Value = vat;
                        prm11.Value = vatsum;
                        prm12.Value = currency;
                        prm14.Value = isk1;
                        prm15.Value = isk2;
                        prm16.Value = isk3;

                        Factory.GetFactory.ExecuteNonQuery(CommandType.Text, insertSql, trn, prm1, prm2, prm3, prm4, prm5, prm6, prm7, prm8, prm9, prm10, prm11, prm12, prm13, prm14, prm15, prm16, prm17); //kayıt vt eklenir.

                    }
                }
            }

            CekilisKontrol(Convert.ToDecimal(txtNetToplam.Text), order_series, order_no, customer_code, trn);

            try
            {
                trn.Commit();
                kaydedildi = true;
            }
            catch (Exception ex)
            {
                trn.Rollback();
                MessageBox.Show(ex.Message);
            }
        }

        private void YeniEvrak()
        {
            kaydedildi = false;
            CellRange rg = new CellRange();
            rg.c1 = 0;
            rg.c2 = c1FlexGrid1.Cols.Count - 1;
            rg.r1 = 1;
            rg.r2 = 199;
            c1FlexGrid1.Clear(C1.Win.C1FlexGrid.ClearFlags.Content, rg);
            txtCariAd.Text = string.Empty;
            txtCariKod.Text = string.Empty;
            c1FlexGrid1.Select(1, 0);
            txtCariKod.Focus();
            txtNetToplam.Text = "0";
            txtAraToplam.Text = "0";
            txtKdvToplam.Text = "0";
            txtGenelToplam.Text = "0";
            txtSeri.Text = "";
            txtSira.Text = "";
            txtAciklama.Text = "";
            txtisk1.Text = "0";
            txtisk2.Text = "0";
            txtisk3.Text = "0";
            txtAciklama.Text = "";
            txtAdres.Text = "";
            txtBolge.Text = "";
            txtTemsilci.Text = "";
            this.EskiEvrak = false;
        }

        private void EvrakOku()
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" SELECT     t1.customer_code, CUSTOMERS.name, PRODUCTS.name as stokad, t1.product_code,t1.barcode, t1.amount, t1.price, t1.total, t1.vat, t1.vatsum,t1.currency, t1.supplier,t1.discount1,t1.discount2,t1.discount3,PRODUCTS.unit,t1.comment,(CUSTOMERS.adress + ' ' + CUSTOMERS.city + ' ' + CUSTOMERS.district) as adress,CUSTOMERS.area_code,CUSTOMERS.seller_person \r\n");
            sb.Append(" FROM         ORDER_DETAILS t1 WITH (NOLOCK) INNER JOIN CUSTOMERS ON t1.customer_code = CUSTOMERS.code INNER JOIN PRODUCTS ON t1.barcode = PRODUCTS.barcode \r\n");
            sb.Append(" WHERE     (t1.order_series = @seri) AND (t1.order_no = @sira) \r\n");

            IDbDataParameter prm1 = Factory.GetFactory.GetParameter("@seri", DbType.String);
            prm1.Value = txtSeri.Text;
            IDbDataParameter prm2 = Factory.GetFactory.GetParameter("@sira", DbType.Int32);
            prm2.Value = int.Parse(txtSira.Text);

            DataTable dt = Factory.GetFactory.ExecuteDataTable(CommandType.Text, sb.ToString(), prm1, prm2);

            CellRange rg = new CellRange();
            rg.c1 = 0;
            rg.c2 = c1FlexGrid1.Cols.Count - 1;
            rg.r1 = 1;
            rg.r2 = c1FlexGrid1.Rows.Count - 1;
            c1FlexGrid1.Clear(ClearFlags.UserData, rg);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                txtCariKod.Text = dt.Rows[i]["customer_code"].ToString();
                txtCariAd.Text = dt.Rows[i]["name"].ToString();

                c1FlexGrid1[i + 1, 0] = dt.Rows[i]["product_code"].ToString();
                c1FlexGrid1[i + 1, 1] = dt.Rows[i]["stokad"].ToString();
                c1FlexGrid1[i + 1, 2] = dt.Rows[i]["amount"].ToString();
                c1FlexGrid1[i + 1, 3] = dt.Rows[i]["unit"].ToString();
                c1FlexGrid1[i + 1, 4] = dt.Rows[i]["price"].ToString();
                c1FlexGrid1[i + 1, 5] = dt.Rows[i]["discount1"].ToString();
                c1FlexGrid1[i + 1, 6] = dt.Rows[i]["discount2"].ToString();
                c1FlexGrid1[i + 1, 7] = dt.Rows[i]["discount3"].ToString();
                c1FlexGrid1[i + 1, 8] = dt.Rows[i]["total"].ToString();
                c1FlexGrid1[i + 1, 9] = dt.Rows[i]["barcode"].ToString();
                c1FlexGrid1[i + 1, 10] = dt.Rows[i]["vat"].ToString();
                c1FlexGrid1[i + 1, 11] = dt.Rows[i]["vatsum"].ToString();
                c1FlexGrid1[i + 1, 12] = dt.Rows[i]["currency"].ToString();


            }

            if (dt.Rows.Count > 0)
            {
                txtAciklama.Text = dt.Rows[0]["comment"].ToString();
                txtAdres.Text = dt.Rows[0]["adress"].ToString();
                txtBolge.Text = dt.Rows[0]["area_code"].ToString();
                txtTemsilci.Text = dt.Rows[0]["seller_person"].ToString();
                kaydedildi = true;
            }

            SubTotal();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            int index = 0;
            foreach (string item in dbListe.CariMessages())
            {
                if (sumbox1.Items.ContainsKey(index))
                {
                    sumbox1.Items[index] = item;
                    sumbox1.CalculateItems();
                    sumbox1.Invalidate();
                }
                else
                {
                    sumbox1.Items.Add(index, item);
                    sumbox1.CalculateItems();
                    sumbox1.Invalidate();
                }
                index++;
            }
        }
        private void txtSeri_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtSira_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            frmListe liste = new frmListe();
            liste.ListeTipi = frmListe.ListeTipleri.EvrakListesi;
            liste.Filtre = txtSeri.Text;
            if (liste.ShowDialog(this) == DialogResult.OK && liste.Values.Count > 0)
            {
                YeniEvrak();
                this.EskiEvrak = true;
                txtSira.Text = liste.Values[0][1];
                txtSeri.Text = liste.Values[0][0];

                EvrakOku();

                c1FlexGrid1.Select(1, 0);
                c1FlexGrid1.Focus();
            }
        }

        private void Yazdir()
        {
            string seri = txtSeri.Text;
            string sira = txtSira.Text;
            prnSiparis prn = new prnSiparis();
            prn.EvrakSeri = seri;
            prn.EvrakSira = int.Parse(sira);
            prn.EvrakYukle(false);
            prn.PrintingSystem.ShowMarginsWarning = false;
            if (!string.IsNullOrEmpty(System.Configuration.ConfigurationSettings.AppSettings["Print"]))
            {
                int printCount = Convert.ToInt32(System.Configuration.ConfigurationSettings.AppSettings["Print"]);
                for (int i = 0; i < printCount; i++)
                {
                    prn.Print();
                }
            }
            else
            {
                prn.PrintDialog();
            }
        }

        private void simpleButton1_Click(object sender, EventArgs e)
        {
            YeniEvrak();
        }

        private void simpleButton2_Click(object sender, EventArgs e)
        {
            Kaydet();
        }

        private void simpleButton3_Click(object sender, EventArgs e)
        {
            if (kaydedildi)
            {
                Yazdir();
                YeniEvrak();
            }
            else
                MessageBox.Show("Kaydedilmemiş Evrak Yazdırılamaz !");
        }

        private void simpleButton4_Click(object sender, EventArgs e)
        {
            if (File.Exists(Application.StartupPath + "\\Reporting.exe"))
            {
                Process.Start(Application.StartupPath + "\\Reporting.exe");
            }
            else
                MessageBox.Show("Raporlama Programı Yüklenmemiş !");
        }

        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {

        }

        private void EvrakSil()
        {
            if (!string.IsNullOrEmpty(txtSeri.Text) && !string.IsNullOrEmpty(txtSira.Text))
            {
                string deleteSql = " delete from ORDER_DETAILS where order_series=@order_series and order_no=@order_no";
                IDbDataParameter prm1 = Factory.GetFactory.GetParameter("@order_series", DbType.String);
                prm1.Value = txtSeri.Text;
                IDbDataParameter prm2 = Factory.GetFactory.GetParameter("@order_no", DbType.Int32);
                prm2.Value = txtSira.Text;
                Factory.GetFactory.ExecuteNonQuery(CommandType.Text, deleteSql, prm1, prm2); //kayıt vt silinir.
            }
        }
        private void btnSil_Click(object sender, EventArgs e)
        {
            DialogResult dlg = MessageBox.Show("Silmek İstediğinize Eminmisiniz !", "", MessageBoxButtons.YesNo);
            if (dlg == DialogResult.Yes)
            {
                EvrakSil();
                YeniEvrak();
            }
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = "";
            dlg.Filter = "Excel Dosyası|*.xls";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                c1FlexGrid1.SaveExcel(dlg.FileName);
            }
        }

        private void simpleButton6_Click(object sender, EventArgs e)
        {
            YeniUrun();
            c1FlexGrid1.Focus();
        }

        private void simpleButton5_Click(object sender, EventArgs e)
        {
            if (c1FlexGrid1.Row > -1 && c1FlexGrid1[c1FlexGrid1.Row, 0] != null)
            {
                frmYeniGiris yeni = new frmYeniGiris();
                yeni.EskiKayit = true;
                yeni.txtBarkod.Text = c1FlexGrid1[c1FlexGrid1.Row, 0].ToString();
                yeni.txtBarkod.Properties.ReadOnly = true;
                yeni.txtKodu.Properties.ReadOnly = true;
                yeni.barkodBul(c1FlexGrid1[c1FlexGrid1.Row, 9].ToString());
                yeni.txtBarkod.Focus();
                if (yeni.ShowDialog() == DialogResult.OK)
                {
                    c1FlexGrid1[c1FlexGrid1.Row, 2] = yeni.Miktar;
                    c1FlexGrid1.Focus();
                }
            }
        }

        private void c1FlexGrid1_AfterRowColChange(object sender, RangeEventArgs e)
        {
            if (c1FlexGrid1[e.NewRange.r1, 1] != null)
            {
                if (c1FlexGrid1[e.NewRange.r1, 1].ToString().IndexOf("CIRO GIRISI") > -1)
                {
                    c1FlexGrid1.Cols[4].AllowEditing = true;
                }
                else
                {
                    c1FlexGrid1.Cols[4].AllowEditing = false;
                }
            }
        }

    }
}
